# Based on https://aur.archlinux.org/packages/mingw-w64-capnproto/
#
# Maintainer: Igor Matuszewski <xanewok@gmail.com>
# Contributors: Dave Reisner <dreisner@archlinux.org>
#               Matthias Blaicher <matthias@blaicher.com>
#               Severen Redwood <severen@shrike.me>
#               Igor Matuszewski <xanewok@gmail.com>

_realname=capnproto
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=0.10.3
pkgrel=2
pkgdesc="Cap'n Proto serialization/RPC system (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url='https://capnproto.org/'
license=('spdx:MIT')
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-openssl"
         "${MINGW_PACKAGE_PREFIX}-zlib")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "unzip")
source=("${_realname}-${pkgver}.zip::https://github.com/capnproto/capnproto/archive/refs/tags/v${pkgver}.zip")
noextract=("${_realname}-${pkgver}.zip")
sha512sums=('871bf4daa658973ac2ae1c0a4a3201c7e4d6972b084981ca8783b048e47c173d917522171867f1cf4438d0c604445e1869d73c27af08680fdead4787e6067ead')

prepare() {
  unzip -q "${_realname}-${pkgver}.zip"
  cd "${srcdir}/${_realname}-${pkgver}"
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G "Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_BUILD_TYPE=Release \
    -DBUILD_SHARED_LIBS=ON \
    ../${_realname}-${pkgver}

  # Help capnpc to find libkj.dll
  PATH=$PWD/c++/src/kj:$PATH ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

check() {
  cd "${srcdir}/build-${MSYSTEM}"
  # Help capnp-tests to find DLLs
  PATH=$PWD/c++/src/capnp:$PWD/c++/src/kj:$PATH ${MINGW_PREFIX}/bin/ctest.exe ./ || warning "Tests failed"
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install ./

  local PREFIX_WIN="$(cygpath -wm ${MINGW_PREFIX})"

  for cmkfile in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/CapnProto/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i "${cmkfile}"
  done

  for pcfile in "${pkgdir}${MINGW_PREFIX}"/lib/pkgconfig/*.pc; do
    sed -s "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pcfile}"
  done

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
